<?php
// +----------------------------------------------------------------------
// | 中联致远服务端框架
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.zhongliansoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: tony <tanyu@zhongliansoft.com>
// +----------------------------------------------------------------------

namespace app\common\model;
use think\Validate;
use app\common\model\BookExtraDraw as BookExtraDrawModel;
use app\common\model\BookAccount as BookAccountModel;
use app\common\model\Config as ConfigModel;
use think\model\concern\SoftDelete;

class StudentTypeBookRel extends Common
{
    protected $rule = [
        'plan_year'     => 'require',
        'plan_season'   => 'require',
        'book_num'      => 'require|number',
    ];

    protected $msg = [
        'plan_year'         => '请选择年份',
        'plan_season'       => '请选择季度',
        'book_num.require'  => '请输入教材数量',
        'book_num.number'   => '教材数量必须是数字',
    ];

    /**
     * 设置csv header
     * @return array
     */
    public function csvHeader()
    {
        return [
            [
                'id'   => 'plan_year',
                'desc' => '年度',
            ],
            [
                'id'   => 'plan_season',
                'desc' => '季度',
            ],
            [
                'id'   => 'type_name',
                'desc' => '类型',
            ],
            [
                'id'   => 'param_name',
                'desc' => '参数',
            ],
            [
                'id'   => 'book_name',
                'desc' => '教材名称',
            ],
            [
                'id'   => 'book_price',
                'desc' => '教材单价',
            ],
            [
                'id'   => 'book_num',
                'desc' => '教材数量',
            ],
            [
                'id'   => 'book_author',
                'desc' => '主编',
            ],
            [
                'id'   => 'book_concern',
                'desc' => '出版社',
            ],
            [
                'id'   => 'book_isbn',
                'desc' => 'ISBN书号',
            ],
            [
                'id'   => 'book_edition',
                'desc' => '版次',
            ],
            [
                'id'   => 'book_date',
                'desc' => '出版年限',
            ],
            [
                'id'   => 'book_reward',
                'desc' => '获奖情况',
            ],
            [
                'id'   => 'description',
                'desc' => '备注',
            ]
        ];
    }


    /**
     * @param $post
     *
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function tableData($post)
    {
        if(isset($post['limit'])){
            $limit = $post['limit'];
        }else{
            $limit = config('paginate.list_rows');
        }

        $tableWhere = $this->tableWhere($post);
        $list = $this->alias('a')
                ->field("a.id, a.plan_year, case when a.plan_season = 1 then '春季' when a.plan_season = 3 then '秋季' end as plan_season, c.name as type_name, d.name as param_name, b.book_name, b.book_author, b.book_concern, b.book_edition,  b.book_isbn, a.book_num, a.price, a.book_disc, b.book_reward, b.book_date ")
                ->join('zl_book_info b', 'a.book_id = b.id')
                ->join('zl_student_type c', 'a.type_id = c.id')
                ->join('zl_student_type_params d', 'a.type_id = d.type_id and a.param_id = d.id')
                ->where($tableWhere['where'])
                ->order($tableWhere['order'])
                ->paginate($limit);
        $data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型

        $re['code'] = 0;
        $re['msg'] = '';
        $re['count'] = $list->total();
        $re['data'] = $data;

        return $re;
    }

    public function exportData($post)
    {
        $tableWhere = $this->tableWhere($post);
        $list = $this->alias('a')
                ->field("a.id, a.plan_year, case when a.plan_season = 1 then '春季' when a.plan_season = 3 then '秋季' end as plan_season, c.name as type_name, d.name as param_name, b.book_name, b.book_author, b.book_concern, b.book_edition,  b.book_isbn, a.book_num, a.price, a.book_disc,  b.book_reward, b.book_date ")
                ->join('zl_book_info b', 'a.book_id = b.id')
                ->join('zl_student_type c', 'a.type_id = c.id')
                ->join('zl_student_type_params d', 'a.type_id = d.type_id and a.param_id = d.id')
                ->where($tableWhere['where'])
                ->order($tableWhere['order'])->select()->toArray();
                //返回的数据格式化，并渲染成table所需要的最终的显示数据类型
        if (count($list) > 0) {
            $result['code'] = 0;
           // $result['count'] = $list->total();
            $result['msg']    = '导出成功';
            $result['data']   = $list;
            return $result;
        } else {
            //失败，导出失败
            return $result;
        }
    
    }

    /**
     * @param $list
     *
     * @return mixed
     */
    public function getBookList()
    {
        $list = $this->alias('a')
                ->field("concat(a.plan_year, '-', case when a.plan_season = 1 then '春季' when a.plan_season = 3 then '秋季' end, '-', c.name, '-', d.name, '-', b.book_isbn) as keyName")
                ->join('zl_book_info b', 'a.book_id = b.id')
                ->join('zl_student_type c', 'a.type_id = c.id')
                ->join('zl_student_type_params d', 'a.type_id = d.type_id and a.param_id = d.id')->select()->toArray();
 
                $nameList = [];
                foreach ($list as $key => $val) {
                    $nameList[] = $val['keyName'];
                }
                
                return $nameList;
    }
    
    /**
     *  添加关联
     * User:tony
     * @param $data
     * @return array
     */
    public function addData($data)
    {
        $result = [
            'status' => true,
            'msg' => '保存成功',
            'data'=> []
        ];

        $validate = new Validate($this->rule,$this->msg);
        if (!$validate->check($data)) {
            $result['status'] = false;
            $result['msg'] = $validate->getError();
        } else {
            // 如果该类型参数已经发放过教材则不允许进行添加
            $bookExtraDrawModel = new BookExtraDrawModel(); 
            $find = $bookExtraDrawModel->where(['year'=>$data['plan_year'], 'season'=>$data['plan_season'], 'type_id'=>$data['type_id'], 'param_id'=>$data['param_id']])->find();

            if($find){
                $result['status'] = false;
                $result['msg'] = '该类型参数已经发放过教材，不允许添加！';   
                return $result;
            }

            // 判断是否存在相同的教材
            $info = $this->where(['plan_year'=>$data['plan_year'], 'plan_season'=>$data['plan_season'], 'type_id'=>$data['type_id'], 'param_id'=>$data['param_id'], 'book_id'=>$data['book_id']])->find();
            if($info){
                $result['status'] = false;
                $result['msg'] = '同类型同参数教材已存在';   
                return $result;
            }
            
            // 不同类型也不允许重复添加
            $where[] = ['plan_year' ,'eq', $data['plan_year']];
            $where[] = ['plan_season' ,'eq', $data['plan_season']];
            $where[] = ['book_id' ,'eq', $data['book_id']];
            $where[] = ['a.type_id' ,'neq', $data['type_id']];
            // 判断是否存在相同的教材
            $infoType = $this->alias('a')->field('b.name typename, c.name paramname')
                    ->join('zl_student_type b', 'a.type_id = b.id')
                    ->join('zl_student_type_params c', 'a.param_id = c.id')
                    ->where($where)
                    ->find();
            if($infoType){
                $result['status'] = false;
                $result['msg'] = $infoType['typename'] . '-' . $infoType['paramname'] . '已存在该教材';   
                return $result;
            }

            if (!$this->allowField(true)->save($data))
            {
                $result['status'] = false;
                $result['msg'] = '保存失败';
            }
        }
        \think\facade\Request::token('__ZlServer_Token__', 'sha1');
        return $result;
    }

    /**
     *  修改关联
     * User:tony
     * @param $data
     * @return array
     */
    public function editData($data)
    {
        $result = [
            'status' => true,
            'msg' => '保存成功',
            'data' => []
        ];
        $validate = new Validate($this->rule,$this->msg);
        if (!$validate->check($data)) {
            $result['status'] = false;
            $result['msg'] = $validate->getError();
        } else {
            $editData['book_num'] = $data['book_num'];
            if (!$this->allowField(true)->save($editData,['id'=>$data['relId']]))
            {
                $result['status'] = false;
                $result['msg'] = '保存失败';
            } else {
                // 更新账表状态
                $list = $this->alias('a')
                ->field('c.xh')
                ->join('zl_book_extra_draw b', 'a.plan_year = b.year and a.plan_season = b.season and a.type_id = b.type_id and a.param_id = b.param_id')
                ->join('zl_book_extra_draw_detail c', 'b.id = c.draw_id')
                ->where(['a.id'=>$data['relId']])
                ->select();
        
                $xhList = [];
                foreach($list as $xhItem) {
                    $xhList[] = $xhItem['xh'];
                }
                $config = new ConfigModel();
                $year = $config->getYear();
                $season = $config->getSeason();

                // 设置账表状态
                // $whereUpdate[] = ['xh', 'in', $xhList];
                // $whereUpdate[] = ['year', 'eq', $year];
                // $whereUpdate[] = ['season', 'eq', $season];
                // $bookAccountModel = new BookAccountModel();
                // $bookAccountModel->save(['status'=>0], $whereUpdate);
                
            }
        }
        \think\facade\Request::token('__ZlServer_Token__', 'sha1');
        return $result;
    }

    //where搜索条件
    protected function tableWhere($post)
    {
        $where = [];
        if(isset($post['year']) && $post['year'] != ""){
            $where[] = ['a.plan_year', 'eq', $post['year']];
        } 
        if(isset($post['season']) && $post['season'] != ""){
            $where[] = ['a.plan_season', 'eq', $post['season']];
        } 
        if(isset($post['type_id']) && $post['type_id'] != ""){
            $where[] = ['a.type_id', 'eq', $post['type_id']];
        } 
        if(isset($post['param_id']) && $post['param_id'] != ""){
            $where[] = ['a.param_id', 'eq', $post['param_id']];
        } 
        $result['where'] = $where;
        $result['field'] = "*";
        $result['order'] = ['a.plan_year', 'a.plan_season', 'a.type_id', 'a.param_id'];
        return $result;
    }

    /**
     * @param $list
     *
     * @return mixed
     */
    protected function tableFormat($list)
    {
        return $list;
    }
}